/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.healthecology.operator;

import com.huawei.healthecology.data.ble.response.BleResponseCode;
import com.huawei.healthecology.data.platform.PlatformCallback;
import com.huawei.healthecology.data.platform.PlatformResponse;
import com.huawei.healthecology.data.utils.OptionalX;
import com.huawei.healthecology.json.GsonMapper;
import com.huawei.healthecology.json.JsonMapper;
import com.huawei.healthecology.log.LogUtil;
import com.huawei.healthecology.module.ClientModule;

import lombok.AllArgsConstructor;
import lombok.Getter;
import ohos.rpc.IRemoteObject;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.rpc.RemoteException;

import java.util.Optional;

/**
 * The remote operator for Js FA
 */
@AllArgsConstructor(staticName = "of")
public class JsRemoteOperator implements PlatformCallback {
    private static final String TAG = "JsRemoteOperator";

    @Getter
    private final IRemoteObject remoteObject;

    private final MessageParcel remoteReplyParcel;

    private final JsonMapper jsonMapper = ClientModule.getParser().orElse(GsonMapper.get());

    /**
     * To reply the direct response
     *
     * @param response The platform response to Js FA
     * @return ture if replay sucess, false otherwise
     */
    public boolean writeResponse(PlatformResponse response) {
        OptionalX.ofNullable(response.getResultData())
            .ifPresent(hasData -> replyFullResponse(response))
            .ifNotPresent(() -> replyCodeOnly(response.getResultCode()));
        return true;
    }

    @Override
    public void onResponse(String response) {
        if (!Optional.ofNullable(remoteObject).isPresent()) {
            LogUtil.error(TAG, "Fail to send back the data, empty remote object");
        }
        MessageParcel replyData = MessageParcel.obtain();
        MessageOption replyOption = new MessageOption();
        MessageParcel replyParcel = MessageParcel.obtain();
        try {
            replyData.writeString(response);
            remoteObject.sendRequest(BleResponseCode.OPERATION_SUCCESS.getValue(), replyData, replyParcel, replyOption);
        } catch (RemoteException e) {
            LogUtil.error(TAG, "Fail to send back the data");
        }
        replyParcel.reclaim();
        replyData.reclaim();
    }

    private void replyFullResponse(PlatformResponse response) {
        jsonMapper.stringify(response).ifPresent(remoteReplyParcel::writeString);
    }

    private void replyCodeOnly(int codeValue) {
        jsonMapper.stringify(PlatformResponse.builder()
            .resultCode(codeValue).build())
            .ifPresent(remoteReplyParcel::writeString);
    }
}
